﻿using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Windows.Forms;

namespace DSClient
{
    public partial class frmClient : Form
    {
        private void DoCommand(string cmd)
        {
            string[] tokens = cmd.Trim().Split(' ');

            switch (tokens[0])
            {
                case "exit":
                case "quit":
                    if (connected)
                        Disconnect();
                    Application.Exit();
                    break;

                case "connect":
                    try
                    {
                        socket = new TcpClient();
                        socket.Connect(tokens[1], port);
                        sr = new StreamReader(socket.GetStream());
                        sw = new StreamWriter(socket.GetStream());

                        listening = true;
                        // Start the receiving thread
                        Thread recThread = new Thread(new ThreadStart(ReceiveThread));
                        recThread.Start();

                        // Send connection request
                        Send("{CONNECT} " + tokens[2] + " " + tokens[3]);
                    }
                    catch (Exception ex)
                    {
                        OutputWriteLine("ERROR (Connect): " + ex.Message);
                    }
                    break;

                case "send":
                    string minusFirst = cmd.Substring(tokens[0].Length + 1);
                    Send(minusFirst);
                    break;

                case "disconnect":
                    Disconnect();
                    break;

                case "clients":
                    Send("{CLIENTS}");
                    break;

                default:
                    Send("{MESSAGE} " + cmd);
                    break;
            }
        }
    }
}
